package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.UpdateProfileEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.CitySelectUtil;
import com.sam.im.heiqun.utils.FileSaveUtil;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCropViewActivity;
import com.sam.im.heiqun.utils.PictureUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.soundcloud.android.crop.Crop;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.data.PrefsUtils;
import com.yuyh.library.utils.io.PhotoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.soundcloud.android.crop.Crop.REQUEST_CROP;


/**
 * 个人设置
 */
public class PersonalInformationActivity extends BaseSwipeBackActivity implements PhotoUtils.OnPhotoResultListener, CitySelectUtil.IOnCitySelectListener {

    private static final int SDK_PERMISSION_REQUEST = 127;
    public final  static  int CHOSE_IMG = 101 ;
    private String choesimgpath;

    public static final int REQUEST_SEX = 1000;
    public static final int REQUEST_NICK = 1001;
    public static final int REQUEST_SIGN = 1002;
    private static final int HEAD_IMG_URL = 1005;

    private static final String TAG = PersonalInformationActivity.class.getSimpleName();

    @BindView(R.id.linear_nick)
    LinearLayout linearNick;
    @BindView(R.id.linear_sex)
    LinearLayout linearSex;
    @BindView(R.id.linear_city)
    LinearLayout linearCity;
    @BindView(R.id.linear_sign)
    LinearLayout linearSign;
    @BindView(R.id.linear_head)
    LinearLayout linearHead;
    @BindView(R.id.linear_qrcode)
    LinearLayout linear_qrcode;

    @BindView(R.id.nick)
    TextView nickName;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.center_title)
    TextView title;
    @BindView(R.id.right_commit)
    TextView commit;

    @BindView(R.id.left_back)
    ImageView backImg;
    @BindView(R.id.head_img)
    ImageView headImg;

    String nickStr;
    String signStr;
    String sexStr;
    String userId;
    String cityStr;
    String province;
    String headImgStr;

    private String photoFileUrl;

    private boolean headImgChanged = false;
    private File headImgFile;
    private PGService mPGservice;
    private Uri imageUri;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HEAD_IMG_URL:
                    updataHeadImg(((String) msg.obj));
                    break;
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_personal_information;
    }

    @Override
    protected String getTitleText() {
        title.setText(R.string.person_info);
        commit.setText(R.string.commit);
        return getResources().getString(R.string.person_info);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
        headImg.setImageResource(R.drawable.register_left);
        initUI();
    }

    @OnClick({R.id.linear_sign, R.id.linear_nick, R.id.linear_sex, R.id.linear_city, R.id.linear_head, R.id.left_back, R.id.right_commit,
            R.id.linear_qrcode})
    public void onClick(View view) {

        Intent intent = new Intent(this, AlterNickSign.class);

        switch (view.getId()) {
            case R.id.linear_nick://修改昵称
                intent.putExtra("title", getResources().getString(R.string.alter_nick));
                intent.putExtra("hint", getResources().getString(R.string.please_input_nick));
                intent.putExtra("state", REQUEST_NICK);
                intent.putExtra("data",nickName.getText().toString());
                startActivityForResult(intent, REQUEST_NICK);
                break;
            case R.id.linear_sign://修改签名
                intent.putExtra("title", getResources().getString(R.string.alter_sign));
                intent.putExtra("hint", getResources().getString(R.string.please_input_sign));
                intent.putExtra("state", REQUEST_SIGN);
                intent.putExtra("data",sign.getText().toString());
                startActivityForResult(intent, REQUEST_SIGN);
                break;
            case R.id.linear_sex://修改性别
                Intent data = new Intent(this, SexSelectActivity.class);
                data.putExtra("sex", sex.getText().toString());
                startActivityForResult(data, REQUEST_SEX);
                break;
            case R.id.linear_city: // 选择城市
                if (isZh()) {
                    CitySelectUtil.showCitySelectDialog(this, this);
                } else {
                    CitySelectUtil.showOverseasSelectDialog(this, this);
                }
                break;
            case R.id.linear_head:
//                String imageName = System.currentTimeMillis() + ".jpg";
//                String imagePath = Environment.getExternalStorageDirectory() + "/" + imageName;
//                imageUri = Uri.fromFile(new File(imagePath));
//                MyDialog.showImgDialog(this, null, imageUri);


                getPersimmions();

                break;
            case R.id.left_back:
                finish();
                break;
            case R.id.right_commit:
                doCommit();
                break;
            case R.id.linear_qrcode:
                Intent intentQR = new Intent(PersonalInformationActivity.this, QRcode.class);
                if (headImgStr != null) {
                    intentQR.putExtra("img", headImgStr);
                }
                startActivity(intentQR);
                break;
        }
    }


    @TargetApi(23)
    protected void getPersimmions() {
        isgo = false ;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)){
                pos ++ ;
            }
            if (2==pos){
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }else {
            gotoPhoto();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                return false;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {

            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
//                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        gotoPhoto();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    boolean isgo = false ;

    private void gotoPhoto(){
        if (!isgo){
            PhotoPickerIntent pt = new PhotoPickerIntent(PersonalInformationActivity.this);
            pt.setSelectModel(SelectModel.MULTI);
            pt.setShowCarema(true); // 是否显示拍照， 默认false
            pt.setMaxTotal(1); // 最多选择照片数量，默认为9
            //pt.setImageConfig(conFig);
            startActivityForResult(pt,CHOSE_IMG);
        }
        isgo = true ;
    }


    /**
     * 启动Activity 的返回值处理
     */
    private Uri newUri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_NICK:
                    nickStr = data.getStringExtra("resultStr");
                    nickName.setText(nickStr);
                    break;
                case REQUEST_SIGN:
                    signStr = data.getStringExtra("resultStr");
                    sign.setText(signStr);
                    break;
                case REQUEST_SEX:
                    sexStr = data.getStringExtra("sex");
                    sex.setText(sexStr);
                    break;

                case 66: {
                    String path = FileSaveUtil.getPath(getApplicationContext(), imageUri);
                    try {
                        Bitmap bitmap = PictureUtil.compressSizeImage(path);
                        bitmap = PictureUtil.reviewPicRotate(bitmap, path);
                        headImgFile = PictureUtil.bitmapToFileJPG(bitmap, path);
                        GlideUtils.loadHeadCircularImage(this, path, headImg);

                        headImgChanged = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
                case REQUEST_CROP:
                     try {
                        //     GlideUtils.loadHeadCircularImage(this, choesimgpath, headImg);
                        headImg.setImageURI(Crop.getOutput(data));

//                        Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
//                        headImgFile = bitmapToFile(bitmap);
                        headImgFile = new File(choesimgpath);
                        headImgChanged = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case 3333:    // 图库选择返回
                {
//                    Uri uri = data.getData();
//                    String path = FileSaveUtil.getPath(getApplicationContext(), uri);
                    try {
                        GlideUtils.loadHeadCircularImage(this, choesimgpath, headImg);
//                        Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
//                        headImgFile = bitmapToFile(bitmap);
                        headImgFile = new File(choesimgpath);
                        headImgChanged = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                }

                case CHOSE_IMG :
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size()>0){
                        choesimgpath = stringArrayListExtra.get(0);

                        int[] imagewh = getImageWidthHeight(choesimgpath);

                        Log.i("info","返回的路径s=="+ choesimgpath);
                        final File file = new File(choesimgpath);
                        if (file.exists()){
                            Uri uri = Uri.fromFile(file);

                            if (imagewh[0] > 600 && imagewh[1] > 600){
//                                ToolsUtils.cropImageUri(this,uri,600,600,3333);
                               // ImageCropViewActivity.start(this,choesimgpath,100,100,3333);
                                newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                                Crop.of(uri, newUri).asSquare().start(this);
                            }else  if (imagewh[0] > imagewh[1] && imagewh[1] > 0){
//                                ToolsUtils.cropImageUri(this,uri,imagewh[1],imagewh[1],3333);
//                                ImageCropViewActivity.start(this,choesimgpath,imagewh[1],imagewh[1],3333);
                                //ImageCropViewActivity.start(this,choesimgpath,100,100,3333);
                                newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                                Crop.of(uri, newUri).asSquare().start(this);
                            }else if (imagewh[1] > imagewh[01] && imagewh[0] > 0){
//                                ToolsUtils.cropImageUri(this,uri,imagewh[0],imagewh[0],3333);
//                                ImageCropViewActivity.start(this,choesimgpath,imagewh[0],imagewh[0],3333);
                               // ImageCropViewActivity.start(this,choesimgpath,100,100,3333);
                                newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                                Crop.of(uri, newUri).asSquare().start(this);
                            }else {
//                                ToolsUtils.cropImageUri(this,uri,600,600,3333);
                               // ImageCropViewActivity.start(this,choesimgpath,100,100,3333);
                                newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                                Crop.of(uri, newUri).asSquare().start(this);
                            }

                        }else {
                            ToolsUtils.showToast(PersonalInformationActivity.this, getResources().getString(R.string.file_no));
                        }
                    }
                    break;
                default:
                    PhotoUtils.setOnPhotoResultListener(this, requestCode, resultCode, data, this);
                    break;
            }
        }
    }

    public static int[] getImageWidthHeight(String path){
        BitmapFactory.Options options = new BitmapFactory.Options();

        /**
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null
        /**
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth,options.outHeight};
    }

    /**
     * 拍照返回信息
     *
     * @param photoPath 照片的路径
     * @param photo     照片原文件
     */
    @Override
    public void onPhotoResult(String photoPath, Bitmap photo) {
        String[] photoses = photoPath.split("camera_photos");
        photoFileUrl = "/storage/emulated/0/" + photoses[1];
        GlideUtils.loadHeadCircularImage(this, photoFileUrl, headImg);

        headImgFile = new File(photoFileUrl);
        headImgChanged = true;
    }

    /**
     * 做 提交
     */
    private void doCommit() {

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }

        showProgressMy(null);
        mPGservice.updateProfile(cityStr, nickStr, province, sexStr, signStr, userId).subscribe(new AbsAPICallback<UpdateProfileEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {

                showToast(getResources().getString(R.string.caozuo_fail));
                finish();
            }

            @Override
            public void onNext(UpdateProfileEntivity updateProfileEntivity) {
                showToast(getResources().getString(R.string.commit_success));
                UserEntivity user = ToolsUtils.getUser();
                user.setName(nickStr);
                user.setCity(cityStr);
                user.setSex(sexStr);
                user.setSign(signStr);
                user.setProvince(province);
                user.save();
                if (headImgChanged) {
                    uploadImage(headImgFile);
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 做 UI 更新
     */
    private void initUI() {
        UserEntivity user = ToolsUtils.getUser();
        userId = user.getId() + "";
        if (null == user.getProvince() || user.getProvince().equals("null")) {
            province = "";
        } else {
            province = user.getProvince();
        }
        if (null == user.getProvince() || user.getProvince().equals("null")) {
            cityStr = "";
        } else {
            cityStr = user.getCity();
        }

        city.setText(province + cityStr);
        if (null == user.getSign() || user.getSign().equals("null")) {
            signStr = "";
        } else {
            signStr = user.getSign();
        }
        sign.setText(signStr);
        if (null == user.getName() || user.getName().equals("null")) {
            nickStr = "";
        } else {
            nickStr = user.getName();
        }
        nickName.setText(nickStr);
        if (null == user.getSex() || user.getSex().equals("null")) {
            sexStr = "";
        } else {
            sexStr = user.getSex();
        }
        sex.setText(sexStr);
        if (null == user.getHeadUrl() || user.getHeadUrl().equals("null")) {
            headImgStr = "";
        } else {
            headImgStr = user.getHeadUrl();
        }
        GlideUtils.loadHeadCircularImage(PersonalInformationActivity.this, headImgStr, headImg);

    }

    /**
     * 上传头像
     */
    public void uploadImage(final File photoFile) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String s = HttpAssist.uploadFile(photoFile,"",false);

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getString("code").equals("1")) {
                        String resultStr = jsonObject.getJSONObject("data").getJSONArray("info").getString(0);
                        Message msg = handler.obtainMessage();
                        msg.what = HEAD_IMG_URL;
                        msg.obj = resultStr;
                        handler.sendMessage(msg);

                    } else {
                        hideProgress();
                        showToast(getResources().getString(R.string.net_visit_exception));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 头像 url 地址更换
     */
    public void updataHeadImg(final String tempUrl) {

        mPGservice.updateHead(tempUrl, userId).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(ex.getDisplayMessage());
                finish();
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {

                GlideUtils.loadHeadCircularImage(PersonalInformationActivity.this, tempUrl, headImg);
                new PrefsUtils(PersonalInformationActivity.this, Constant.HEAD_IMG).put(Constant.HEAD_IMG, tempUrl);
                //修改头像成功后需要更改本地的头像信息
                UserEntivity user = ToolsUtils.getUser();
                user.setHeadUrl(tempUrl);
                user.save();

                hideProgress();
                finish();

            }
        });
    }

    /**
     * 城市选择之后，返回城市的操作
     */
    @Override
    public void onCitySelect(String province, String city) {
        if (isZh()) {
            this.province = province;
            cityStr = city;
            this.city.setText(province + " " + city);
        } else {
            cityStr = province;
            this.province = "";
            this.city.setText(cityStr);
        }
    }

    /**
     * 图片 转为 文件
     */
    public File bitmapToFile(Bitmap bitmap) {
        FileOutputStream fileOutStream = null;
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory(), "headImg.png");
            fileOutStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutStream); // 把位图输出到指定的文件中
            fileOutStream.flush();
            fileOutStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }

    private boolean isZh() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

}
